package com.heima.reggie.controller;

import com.heima.reggie.bean.User;
import com.heima.reggie.common.R;
import com.heima.reggie.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value ="用户登录")
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String code = map.get("code");
        int row=0;
        User user = userService.selectByPhone(phone,code);
        if ("0".equals(user.getPhone())) {
            return R.error("验证码错误！");
        }
        else if (user == null) {
            row = userService.add(new User(phone));
                /*if (add > 0) {
                    user=userService.selectByPhone(phone);
                }*/
            if (row == 0) {
                return R.error("登录失败！");

            }
            }
        session.setAttribute("user", user);
        redisTemplate.delete(phone);
        return R.success(user.getName() + "登录成功！");



    }
}
